import { getNewCartGoods, metgeCart, getCartList, addCartList, deleteCartList, editCart, isCheckAll } from '@/api/carts.js'
// 购物模块
export default {
  namespaced: true,
  state() {
    return {
      list: []
    }
  },
  getters: {
    // 有效商品列表
    validList(state) {
      // 有效商品：库存大于0，商品有效的标识为ture
      return state.list.filter(goods => goods.stock > 0 && goods.isEffective)
    },
    // 失效商品
    loseEfficacyList(state) {
      return state.list.filter(goods => goods.stock < 0 || !goods.isEffective)
    },
    // 以选择商品列表数据
    validSelectList(state, getters) {
      return getters.validList.filter(goods => goods.selected && goods.isEffective)
    },
    // 已选商品的商品列表总件数
    validSelectTotalNumber(state, getters) {
      return getters.validSelectList.reduce((p, c) => p + c.count, 0)
    },
    // 已选择有效商品的总金额
    validselectTotalPirce(state, getters) {
      return getters.validSelectList.reduce((p, c) => p + parseInt(c.nowPrice * 100) * c.count, 0) / 100
    },
    // 是否全选isCheckAll
    isCheckAll(state, getters) {
      return getters.validSelectList.length === getters.validList.length && getters.validList.length !== 0
    },
    // 有效商品的总件数
    validTotalNumber(state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品的总金额
    validTotalPirce(state, getters) {
      return getters.validList.reduce((p, c) => p + parseInt(c.nowPrice * 100) * c.count, 0) / 100
    }
  },
  mutations: {
    // 插入购物车
    insertCart(state, payload) {
      // id skuID name attrsText picture price nowPrice selected stock count isEffective
      // 插入是否有相同商品
      // 1.先找下是否有相同商品
      // 2.如果有相同的商品，查询它的数量，累加到payload上，在保存最新位置
      // 3.如果没有相同商品，保存在最新位置即可
      const sameIndex = state.list.findIndex(item => item.skuId === payload.skuId)
      if (sameIndex > -1) {
        const count = state.list[sameIndex].count
        payload.count += count
        // 删除原有的商品
        state.list.splice(sameIndex, 1)
      }
      // s追加新的
      state.list.unshift(payload)
    },
    // 跟新购物车
    updateCart(state, goods) {
      // goods 商品信息：nowPrice stock isEffective
      // goods 商品对象字段不固定，对象中有哪些数据就改哪些数据，字段的值合理才改
      // goods 商品对象 必需有skuId
      // updateGoods类型=[{}]
      // goods 类型= {}
      const updateGoods = state.list.find(item => item.skuId === goods.skuId)
      for (const key in goods) {
        if (goods[key] !== undefined && goods[key] !== null && goods[key] !== '') {
          updateGoods[key] = goods[key]
        }
      }
    },
    // 删除购物车
    deleteCartList(state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 设置购物车
    setCart(state, payload) {
      // payload 为空就清空，有值就是从新设置购物车
      state.list = payload
    }
  },
  actions: {
    // 合并购物车
    async metgeCart({ commit, state }) {
      const dartList = state.list.map(goods => {
        return {
          skuId: goods.skuId,
          selected: goods.selected,
          count: goods.count
        }
      })
      await metgeCart(dartList)
      // 合并成功
      commit('setCart', [])
    },
    // 添加购物车
    insertCart({ commit, rootState }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 已登录
          addCartList({ skuId: payload.skuId, count: payload.count }).then(() => {
            getCartList().then(data => {
              commit('setCart', data.result)
              resolve()
            })
          })
        } else {
          // 未登录
          commit('insertCart', payload)
          resolve()
        }
      })
    },
    // 根据后台更新购物车(获取商品列表)
    findCart({ commit, rootState, state }) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 已登录获取购物车列表
          getCartList().then(data => {
            commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录// 同时发送请求等所有请求成功一并修改本地数据
          // Promise.all()
          const promiseArr = state.list.map(item => {
            // 返回接口函数的调用
            return getNewCartGoods(item.skuId)
          })
          Promise.all(promiseArr).then(dataArr => {
            dataArr.forEach((data, i) => {
              commit('updateCart', { skuId: state.list[i].skuId, ...data.result })
            })
            resolve()
          }).catch(e => {
            reject(e)
          })
        }
      })
    },
    // 删除购物车
    deleteCartList({ commit, rootState }, payload) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录
          deleteCartList([payload]).then(() => {
            commit('deleteCartList', payload)
            resolve()
          })
        } else {
          // 未登录
          commit('deleteCartList', payload)
          resolve()
        }
      })
    },
    // 修改购物车（选择状态，数量）
    updateCart({ commit, rootState, state }, payload) {
      return new Promise((resolve, reject) => {
        // paload 需要：必须有skuId,可能selected count payload={skuId:'',selected:''}或{skuId:'',count:''}
        if (rootState.user.profile.token) {
          // 已登录
          editCart(payload).then(() => {
            getCartList().then(data => {
              commit('setCart', data.result)
              resolve()
            })
          })
        } else {
          // 未登录
          commit('updateCart', payload)
          resolve()
        }
      })
    },
    // 全选列表
    checkAllCart({ commit, rootState, state, getters }, selected) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 已登录
          const ids = getters.validList.map(item => item.skuId)
          isCheckAll({ selected, ids }).then(() => {
            getCartList().then(data => {
              commit('setCart', data.result)
              resolve()
            })
          })
          resolve()
        } else {
          // 未登录
          getters.validList.forEach(goods => {
            commit('updateCart', { skuId: goods.skuId, selected: selected })
          })
          resolve()
        }
      })
    },
    // 批量删除购物车(有效和无效的商品)
    batchDeleteCart({ commit, rootState, state, getters }, isClear) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录
          const list = getters[isClear ? 'loseEfficacyList' : 'validList'].filter(item => {
            return item.selected === true
          })
          const ids = list.map(item => item.skuId)
          deleteCartList(ids).then(() => {
            getCartList().then(data => {
              commit('setCart', data.result)
              resolve()
            })
          })
        } else {
          // 未登录
          // isClear为true为失效商品，false为有效商品
          const list = getters[isClear ? 'loseEfficacyList' : 'validList'].filter(item => {
            return item.selected === true
          })
          list.forEach(item => {
            commit('deleteCartList', item.skuId)
          })
          resolve()
        }
      })
    },
    // 修改规格
    updateCartSku({ commit, rootState, state, getters }, { newSku, oldSkuId }) {
      return new Promise((resolve, reject) => {
        if (rootState.user.profile.token) {
          // 登录
          // 1.找出旧的商品
          // 2.删除旧的商品
          // 3.原先商品的数量+新skuId
          // 4.添加新的商品
          const oldGoods = state.list.find(item => item.skuId === oldSkuId)
          // 删除旧的商品
          console.log(newSku)
          deleteCartList([oldSkuId]).then(() => {
            // 插入新的规格商品
            return addCartList({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(() => {
            // 插入成功 获取后台购物车数据
            return getCartList()
          }).then(data => {
            commit('setCart', data.result)
            resolve()
          })
        } else {
          // 未登录
          // 找出旧的商品信息
          // 删除旧的商品信息
          // 根据新的sku信息和就的商品信息，合并成一条新的购物车信息
          const oldGoods = state.list.find(item => item.skuId === oldSkuId)
          commit('deleteCartList', oldSkuId)
          const { skuId, price: nowPrice, specsText: attrsText, inventory: stock } = newSku
          // 修改以前的数据
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, stock }
          // 插入新的商品
          commit('insertCart', newGoods)
          resolve()
        }
      })
    }
  }
}
